package com.yf.system.modules.login.ding;


import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.yf.ability.login.dingtalk.config.DingTalkConfig;
import com.yf.ability.login.dingtalk.dto.response.DingUserRespDTO;
import com.yf.ability.login.dingtalk.service.DingLoginService;
import com.yf.ability.login.wechat.dto.response.WxUrlRespDTO;
import com.yf.ability.shiro.dto.SysUserLoginDTO;
import com.yf.base.api.api.ApiRest;
import com.yf.base.api.api.controller.BaseController;
import com.yf.system.modules.user.UserUtils;
import com.yf.system.modules.user.enums.LoginType;
import com.yf.system.modules.user.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 微信登录后台处理类
 * @author bool
 */
@Log4j2
@Api(tags = {"钉钉授权登录"})
@RestController
public class DingTalkLoginController extends BaseController {

    @Autowired
    private DingLoginService dingLoginService;

    @Autowired
    private DingTalkConfig dingTalkConfig;

    @Autowired
    private SysUserService sysUserService;



    /**
     * 网页授权链接地址
     */
    private final static String OAUTH_URL = "https://login.dingtalk.com/oauth2/auth?" +
            "redirect_uri={redirect}" +
            "&response_type=code" +
            "&client_id={appKey}" +
            "&scope=openid" +
            "&state={state}" +
            "&prompt=consent";

    /**
     * 浏览器外部网站扫码进入
     * @return
     */
    @PostMapping("/api/common/ding-talk/get-url")
    @ApiOperation(value = "获取钉钉扫码登录地址", notes = "适应PC场景")
    public ApiRest<WxUrlRespDTO> oAuthUrl() {

        // state为登录跳转标识，可以跳转到h5页面
        String url = OAUTH_URL
                .replace("{appKey}", dingTalkConfig.getAppKey())
                .replace("{redirect}", dingTalkConfig.getRedirect())
                .replace("{state}", IdWorker.getIdStr());

        WxUrlRespDTO respDTO = new WxUrlRespDTO();
        respDTO.setUrl(url);
        return success(respDTO);
    }

    /**
     * 浏览器外部网站扫码进入
     * @param authCode
     * @return
     */
    @GetMapping("/api/common/ding-talk/redirect")
    @ApiOperation(value = "钉钉登录跳转地址", notes = "适应PC场景")
    public ModelAndView webRedirect(@RequestParam("authCode") String authCode) {

        // 获取会话
        DingUserRespDTO resp = dingLoginService.login(authCode);


        SysUserLoginDTO loginDTO = sysUserService.loginByThird(LoginType.DING_TALK, resp.getOpenId(), resp.getNick(), resp.getAvatarUrl());
        ModelAndView mv = new ModelAndView("sync");
        mv.addObject("token", loginDTO.getToken());
        mv.addObject("sec", 2);
        mv.addObject("callback", "/");
        return mv;
    }


    /**
     * 在钉钉环境内进行免登陆
     * @return
     * @throws Exception
     */
    @GetMapping("/api/connect/ding")
    @ApiOperation(value = "钉钉同步跳转地址", notes = "直接将此URL嵌入到钉钉的工作台里面，需要管理员在钉钉后台创建应用")
    public void connect(HttpServletResponse response) throws IOException {

        // 如果登录，直接去首页
        if(UserUtils.isLogin()){
            response.sendRedirect("/");
            return;
        }

        // state为登录跳转标识，可以跳转到h5页面
        String url = OAUTH_URL
                .replace("{appKey}", dingTalkConfig.getAppKey())
                .replace("{redirect}", dingTalkConfig.getRedirect())
                .replace("{state}", IdWorker.getIdStr());

        response.sendRedirect(url);
    }
}
